/*
 * Copyright (c) 2009 Team TypeZero
 *
 * This file is part of ZebBowling
 *
 * ZebBowling is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ZebBowling is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ZebBowling. If not, see <http://www.gnu.org/licenses/>.
 **/

package org.zebbowling.control;

import com.sun.spot.util.Utils;
import com.typezero.control.host.ControllerBaseStation;
import com.typezero.control.host.ControllerConnection;
import java.util.LinkedList;
import org.zebbowling.world.SpotBowlingLane;

/**
 * Extension of {@link ControllerBaseStation} to control game flow in
 * Zebulon Bowling.
 *
 * @author Joel Jauregui
 * @deprecated This class isn't neccesary anymore due new implementation where
 * players control the game flow instead of {@link #controlOrder()}. Keep here
 * for reference of the wrong(note bad) way to implement control flow.
 */
public class ZBowlingCBS extends ControllerBaseStation {
   
    private LinkedList queue;
    private SpotBowlingLane alley;
    private int players;

    /**
     * Creates a <tt>ZBowlingCBS</tt> to be used to control game flow in
     * Zebulon Bowling.
     * @param lane The {@link SpotBowlingLane} associated with this basestation.
     */
    public ZBowlingCBS(SpotBowlingLane lane) {
        queue = new LinkedList();
        alley = lane;
        players = 1;
        }

    /**
     * NOTE: This method should be called <br>AFTER you open AT LEAST ONE</br>
     * {@link ControllerConnection}. This method upon being called will control
     * the game flow of the controllers to match the game.
     */
    public void controlOrder() {
        queue.add(connections.get(0));
        while(true) {
            ControllerConnection cc = (ControllerConnection) queue.poll();
            ZBowlingController zbc = (ZBowlingController) cc.getController();            
            zbc.setSuspened(false);
            while(!zbc.getSuspended()) {
                if(players < 2 && alley.playersMade()) {
                    int i;
                    for(i = 1; i < alley.getPlayerCount(); i++)
                        queue.add(connections.get(i));
                    for(; i < connections.size(); i++)
                        ((ControllerConnection)connections.get(i)).getController().stop();
                    players = alley.getPlayerCount();
                    }
                Utils.sleep(10);
                }
            queue.add(cc);                    
            }
        }

    }
